#pragma once
#include <iostream>
#include<string>
#include<functional>
#include"socket.hpp"
#include"InetAddr.hpp"
#include"Protocol.hpp"
using namespace socket_ns;
using process_t=std::function<std::shared_ptr<Response>(std::shared_ptr<Request>)> ;
class IOService
{
public:
    IOService(process_t process)
    :_process(process)
    {
    }
    ~IOService()
    {
    }
    void IOExcute(SockSPtr socket,InetAddr& client)
    {
        std::string packagestreamqueue;
        while(true)
        {
            int n=socket->Recv(&packagestreamqueue);
            if(n<=0)
            {
                LOG(INFO,"client %s quit or recv err\n",client.AddrStr().c_str());
                break;
            }
            //从流里读取的，不一定正好是一条完整的信息
            std::cout<<"packagestreamqueue: "<<packagestreamqueue<<std::endl;
            //去掉报头
            std::string package=Decode(packagestreamqueue);
            //说明读取的数据不完整
            if(package.empty())
            continue;
            //到这package中一定是一条完整序列化的信息
            std::cout<<"package: "<<package<<std::endl;
            auto req=Factory::BuildRequestDefault();
            req->DeSerialize(package);
            //业务处理
            auto resp=_process(req);

            //序列化数据应答
            std::string respjson;
            resp->Serialize(&respjson); //序列化
            respjson=Encode(respjson);//添加报头
            socket->Send(respjson); //发送数据
        }
    }
private:
    //计算业务
    process_t _process;
};